{% extends 'base.html' %}
{% load static %}

{% block title %}{% if template %}编辑模板 - {{ template.name }}{% else %}创建模板{% endif %} - CFS Web System{% endblock %}

{% block page_type %}template-edit{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item"><a href="{% url 'dashboard:dashboard' %}">仪表板</a></li>
<li class="breadcrumb-item"><a href="{% url 'template_management:template_list' %}">模板列表</a></li>
{% if template %}
<li class="breadcrumb-item"><a href="{% url 'template_management:template_detail' template.id %}">{{ template.name }}</a></li>
<li class="breadcrumb-item active">编辑</li>
{% else %}
<li class="breadcrumb-item active">创建模板</li>
{% endif %}
{% endblock %}

{% block content %}
<form id="template-form" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    
    <div class="row">
        <!-- 主要内容 -->
        <div class="col-lg-8">
            <!-- 基本信息 -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-info-circle me-2"></i>基本信息
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-8">
                            <div class="mb-3">
                                <label class="form-label">模板名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="name" id="template-name" 
                                       value="{{ template.name|default:'' }}" required>
                                <div class="form-text">模板的唯一标识名称</div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">状态</label>
                                <select class="form-select" name="is_active" id="template-status">
                                    <option value="true" {% if template.is_active %}selected{% endif %}>启用</option>
                                    <option value="false" {% if not template.is_active %}selected{% endif %}>禁用</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" name="description" id="template-description" rows="3">{{ template.description|default:'' }}</textarea>
                        <div class="form-text">模板的详细描述和用途说明</div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">文件类型</label>
                                <select class="form-select" name="file_type" id="file-type">
                                    <option value="excel" {% if file_type == 'excel' %}selected{% endif %}>Excel文件</option>
                                    <option value="csv" {% if file_type == 'csv' %}selected{% endif %}>CSV文件</option>
                                    <option value="text" {% if file_type == 'text' %}selected{% endif %}>文本文件</option>
                                    <option value="mixed" {% if file_type == 'mixed' %}selected{% endif %}>混合类型</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">输出格式</label>
                                <select class="form-select" name="output_format" id="output-format">
                                    <option value="xlsx" {% if output_format == 'xlsx' %}selected{% endif %}>Excel (.xlsx)</option>
                                    <option value="csv" {% if output_format == 'csv' %}selected{% endif %}>CSV (.csv)</option>
                                    <option value="json" {% if output_format == 'json' %}selected{% endif %}>JSON (.json)</option>
                                    <option value="xml" {% if output_format == 'xml' %}selected{% endif %}>XML (.xml)</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 数据源配置（JSON 编辑） -->
            <div class="card mt-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-database me-2"></i>数据源配置</h5>
                </div>
                <div class="card-body">
                    <div class="mb-2 text-muted small">以 JSON 格式编辑数据源数组。当为空时可留空 []。</div>
                    <textarea id="data-sources-json" class="form-control json-editor" rows="10" placeholder='[\n  {\n    "name": "主数据文件",\n    "type": "excel",\n    "file_key": "main_file",\n    "sheet_name": "Sheet1"\n  }\n]'></textarea>
                </div>
            </div>

            <!-- 处理规则（JSON 编辑） -->
            <div class="card mt-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-cogs me-2"></i>处理规则</h5>
                </div>
                <div class="card-body">
                    <div class="mb-2 text-muted small">以 JSON 格式编辑处理规则数组；不同规则类型请参考创建页示例。</div>
                    <textarea id="processing-rules-json" class="form-control json-editor" rows="10" placeholder='[\n  {\n    "rule_type": "field_mapping",\n    "source_name": "主数据文件",\n    "mappings": []\n  }\n]'></textarea>
                </div>
            </div>

            <!-- 输出配置（JSON 编辑） -->
            <div class="card mt-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-file-export me-2"></i>输出配置</h5>
                </div>
                <div class="card-body">
                    <div class="mb-2 text-muted small">以 JSON 格式编辑输出配置数组；常见字段：source_name、sheet_name、include_header、start_row、start_col。</div>
                    <textarea id="output-configs-json" class="form-control json-editor" rows="8" placeholder='[\n  {\n    "name": "默认输出",\n    "type": "excel",\n    "output_config": {\n      "source_name": "处理结果",\n      "sheet_name": "Sheet1",\n      "include_header": true,\n      "start_row": 1,\n      "start_col": "A"\n    }\n  }\n]'></textarea>
                </div>
            </div>
        </div>
        
        <!-- 侧边栏 -->
        <div class="col-lg-4">
            <!-- 操作面板 -->
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-save me-2"></i>保存选项
                    </h6>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-success" id="save-btn">
                            <i class="fas fa-save"></i> {% if template %}更新模板{% else %}创建模板{% endif %}
                        </button>
                        

                        
                        <button type="button" class="btn btn-outline-secondary" onclick="saveDraft()">
                            <i class="fas fa-file-alt"></i> 保存草稿
                        </button>
                        
                        <hr>
                        
                        <a href="{% if template %}{% url 'template_management:template_detail' template.id %}{% else %}{% url 'template_management:template_list' %}{% endif %}" 
                           class="btn btn-outline-secondary">
                            <i class="fas fa-times"></i> 取消
                        </a>
                    </div>
                </div>
            </div>
            
            <!-- 字段类型说明 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-question-circle me-2"></i>字段类型说明
                    </h6>
                </div>
                <div class="card-body">
                    <div class="field-type-help">
                        <div class="help-item">
                            <strong>text</strong> - 单行文本输入
                        </div>
                        <div class="help-item">
                            <strong>number</strong> - 数字输入
                        </div>
                        <div class="help-item">
                            <strong>select</strong> - 下拉选择
                        </div>
                        <div class="help-item">
                            <strong>checkbox</strong> - 复选框
                        </div>
                        <div class="help-item">
                            <strong>textarea</strong> - 多行文本
                        </div>

                        <div class="help-item">
                            <strong>date</strong> - 日期选择
                        </div>
                    </div>
                </div>
            </div>
            

            
            {% if template %}
            <!-- 模板信息 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-info me-2"></i>模板信息
                    </h6>
                </div>
                <div class="card-body">
                    <table class="table table-sm">
                        <tr><td>创建时间:</td><td>{{ template.created_at|date:'Y-m-d H:i' }}</td></tr>
                        <tr><td>更新时间:</td><td>{{ template.updated_at|date:'Y-m-d H:i' }}</td></tr>
                        <tr><td>使用次数:</td><td>{{ template.usage_count }}</td></tr>
                        <tr><td>版本:</td><td>v{{ template.version|default:'1.0' }}</td></tr>
                    </table>
                </div>
            </div>
            {% endif %}
        </div>
    </div>
</form>


{% endblock %}

{% block extra_js %}
<script>
// 页面状态
let processingRules = {{ processing_rules_json|safe }};
let dataSources = {{ data_sources_json|default:"[]"|safe }};
let outputConfigs = {{ output_configs_json|default:"[]"|safe }};

// 新增：JSON 工具与初始化
function safeStringify(obj) {
    try { return JSON.stringify(obj || [], null, 2); } catch (e) { return '[]'; }
}
function safeParseJSONArray(text) {
    const t = (text || '').trim();
    if (!t) return [];
    const parsed = JSON.parse(t);
    if (!Array.isArray(parsed)) {
        throw new Error('JSON 根节点必须是数组');
    }
    return parsed;
}
function initializeJsonEditors() {
    const ds = document.getElementById('data-sources-json');
    if (ds) ds.value = safeStringify(dataSources);
    const pr = document.getElementById('processing-rules-json');
    if (pr) pr.value = safeStringify(processingRules);
    const oc = document.getElementById('output-configs-json');
    if (oc) oc.value = safeStringify(outputConfigs);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeTemplatePage();
});

// 初始化模板编辑页面
function initializeTemplatePage() {
    // 初始化 JSON 编辑器
    initializeJsonEditors();
    
    // 表单提交事件
    document.getElementById('template-form').addEventListener('submit', function(e) {
        e.preventDefault();
        saveTemplate();
    });

    // 初始化代码编辑器（如果需要）
    initializeCodeEditor();
}

// 保存模板
function saveTemplate() {
    const formEl = document.getElementById('template-form');
    const formData = new FormData(formEl);

    // 从 JSON 文本域读取并校验
    try {
        const dsEl = document.getElementById('data-sources-json');
        const prEl = document.getElementById('processing-rules-json');
        const ocEl = document.getElementById('output-configs-json');
        if (dsEl) dataSources = safeParseJSONArray(dsEl.value);
        if (prEl) processingRules = safeParseJSONArray(prEl.value);
        if (ocEl) outputConfigs = safeParseJSONArray(ocEl.value);
    } catch (e) {
        CFS.utils.showNotification('配置 JSON 解析失败: ' + e.message, 'error');
        return;
    }

    // 追加三大配置
    formData.append('data_sources', JSON.stringify(dataSources || []));
    formData.append('processing_rules', JSON.stringify(processingRules || []));
    formData.append('output_configs', JSON.stringify(outputConfigs || []));

    const saveBtn = document.getElementById('save-btn');
    const originalText = saveBtn.innerHTML;
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';

    const url = '{% if template %}/template-management/templates/{{ template.id }}/edit/{% else %}/template-management/templates/create/{% endif %}';
    
    fetch(url, {
        method: 'POST',
        headers: { 'X-CSRFToken': CFS.utils.getCsrfToken() },
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('模板已保存', 'success');
            {% if not template %}
            setTimeout(() => {
                window.location.href = '/template-management/templates/' + data.template_id + '/';
            }, 1000);
            {% endif %}
        } else {
            CFS.utils.showNotification('保存失败: ' + data.error, 'error');
        }
    })
    .catch(err => CFS.utils.showNotification('保存失败: ' + err.message, 'error'))
    .finally(() => {
        saveBtn.disabled = false;
        saveBtn.innerHTML = originalText;
    });
}

// 保存草稿
function saveDraft() {
    const formData = new FormData(document.getElementById('template-form'));

    // 从 JSON 文本域读取并校验
    try {
        const dsEl = document.getElementById('data-sources-json');
        const prEl = document.getElementById('processing-rules-json');
        const ocEl = document.getElementById('output-configs-json');
        if (dsEl) dataSources = safeParseJSONArray(dsEl.value);
        if (prEl) processingRules = safeParseJSONArray(prEl.value);
        if (ocEl) outputConfigs = safeParseJSONArray(ocEl.value);
    } catch (e) {
        CFS.utils.showNotification('配置 JSON 解析失败: ' + e.message, 'error');
        return;
    }

    formData.append('data_sources', JSON.stringify(dataSources || []));
    formData.append('processing_rules', JSON.stringify(processingRules || []));
    formData.append('output_configs', JSON.stringify(outputConfigs || []));
    formData.append('save_as_draft', 'true');
    
    fetch('{% if template %}/template-management/templates/{{ template.id }}/edit/{% else %}/template-management/templates/create/{% endif %}', {
        method: 'POST',
        headers: { 'X-CSRFToken': CFS.utils.getCsrfToken() },
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('草稿已保存', 'success');
        } else {
            CFS.utils.showNotification('保存草稿失败: ' + data.error, 'error');
        }
    })
    .catch(err => CFS.utils.showNotification('保存草稿失败: ' + err.message, 'error'));
}

// 代码编辑器相关：Tab 键输入四个空格
const codeEditor = document.getElementById('code-editor');
if (codeEditor) {
    codeEditor.addEventListener('keydown', function(e) {
        if (e.key === 'Tab') {
            e.preventDefault();
            const start = this.selectionStart;
            const end = this.selectionEnd;
            this.value = this.value.substring(0, start) + '    ' + this.value.substring(end);
            this.selectionStart = this.selectionEnd = start + 4;
        }
    });
}

// 生成处理逻辑JSON（占位）
function generateProcessingLogic() {
    const processingLogic = {};
    return JSON.stringify(processingLogic, null, 2);
}

// 显示确认对话框
function showConfirm(message, title = '确认操作', confirmText = '确定', cancelText = '取消') {
    return new Promise((resolve) => {
        const modalId = 'confirm-modal-' + Date.now();
        const modalHtml = `
            <div class="modal fade" id="${modalId}" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">${title}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <p>${message}</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">${cancelText}</button>
                            <button type="button" class="btn btn-danger confirm-btn">${confirmText}</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        const modal = new bootstrap.Modal(document.getElementById(modalId));
        
        document.querySelector(`#${modalId} .confirm-btn`).addEventListener('click', () => {
            modal.hide();
            resolve(true);
        });
        
        document.getElementById(modalId).addEventListener('hidden.bs.modal', function() {
            if (!this.dataset.resolved) {
                resolve(false);
            }
            this.remove();
        });
        
        document.querySelector(`#${modalId} .confirm-btn`).addEventListener('click', () => {
            document.getElementById(modalId).dataset.resolved = 'true';
        });
        
        modal.show();
    });
}
</script>
{% endblock %}